import QtQuick 2.15
import QtQuick.Controls 2.15
import CustomizedComponents

Item {
    id: root

    // 颜色属性
    property color normalColor: "transparent"     // 正常颜色
    property double darkerFactor: 0.1
    property bool isHovered: false
    property color hoveredColor: Qt.darker(normalColor, 1 + darkerFactor)    // 悬浮颜色
    property bool isChecked: false
    property color checkedColor: Qt.darker(normalColor, 1 + 2*darkerFactor)    // 按下颜色

    // 圆角
    property int radius: 10
    property list<int> radiusList: [radius, radius, radius, radius]

    // 动画时间
    property int animationDuration: 100

    // 信号
    signal clicked
    signal pressed
    signal released

    FreeRadiusRec {
        id: freeRadiusRec
        anchors.fill: parent
        radiusList: root.radiusList
        backgroundColor: normalColor
    }

    MouseArea {
        id: mouseArea
        anchors.fill: parent

        Connections{
            target: mouseArea
            onClicked: {
                if (root.isChecked) {
                    root.isChecked = false
                }
                else {
                    root.isChecked = true
                }

                root.clicked()
            }
        }

        HoverHandler {
            id: hoveredHandler

            onHoveredChanged: {
                root.isHovered = hovered;
            }
        }
    }

    states: [
        State {
            name: ""
            PropertyChanges {
                target: freeRadiusRec
                backgroundColor: root.normalColor
            }
        },

        State {
            name: "hovered"
            PropertyChanges {
                target: freeRadiusRec
                backgroundColor: root.hoveredColor
            }
        },

        State {
            name: "checked"
            PropertyChanges {
                target: freeRadiusRec
                backgroundColor: root.checkedColor
            }
        }
    ]

    transitions: [
        Transition {
            from: "*"
            to: "*"

            ColorAnimation {
                target: freeRadiusRec
                properties: 'backgroundColor'
                duration: root.animationDuration
            }
        }
    ]

    onIsHoveredChanged: {
        buttonStateChanged()
    }
    onIsCheckedChanged: {
        buttonStateChanged()
    }

    function buttonStateChanged(){
        if(root.isChecked){
            root.state = "checked"
        }
        else if(root.isHovered){
            root.state = "hovered"
        }
        else{
            root.state = ""
        }
    }
}
